<template>
  <div class="container">
    <el-form ref="ruleFormRef" style="max-width: 100%;margin-left: 10%;" :model="ruleForm" status-icon :rules="rules"
      label-width="auto" class="demo-ruleForm">

      <el-form-item label="请输入原密码" prop="originalPwd">
        <el-input style="width: 250px;" v-model="ruleForm.originalPwd" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="请输入新密码" prop="newPwd">
        <el-input style="width: 250px;" v-model="ruleForm.newPwd" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="请再次输入密码" prop="newPwd2">
        <el-input style="width: 250px;" v-model="ruleForm.newPwd2" type="password" autocomplete="off" />
      </el-form-item>

      <el-form-item>
        <el-button style="margin-left: 23%;margin-top: 10px;" type="primary"
          @click="submitForm(ruleFormRef)">
          修改
        </el-button>
        <el-button style="margin-left: 20px;margin-top: 10px;"
          @click="router.go(-1)">
          返回
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
    
<script lang="ts" setup>
import { reactive, ref, onMounted, onUnmounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus';
import { UpdateApi } from '@/api/api';
import router from '@/router';
// 格式化时间的方法  去掉T
const formatTime = (time: string) => {
  if (!time) return '';
  return time.replace('T', ' ');
}

// 表单的数据
const ruleForm = reactive({
  originalPwd: '',
  newPwd: '',
  newPwd2: '',
})

//声明表单对象名称，关联整个表单中的元素
const ruleFormRef = ref<FormInstance>()

//密码校验
const checkOriginalPwd = (rules: any, value: any, callback: any) => {
  rules
  if (!value) {
    return callback(new Error('密码不能为空'))
  }
  let reg = /^[a-zA-Z0-9]{6,}$/;
  // 密码长度校验
  if (!reg.test(value)) {
    return callback(new Error('密码长度必须大于等于6位，且只能包含字母和数字'));
  }
  return callback(); // 校验通过
}

//新密码校验
const checkPwd = (rules: any, value: any, callback: any) => {
  rules
  if (!value) {
    return callback(new Error('输入不能为空'))
  }
  let reg = /^[a-zA-Z0-9]{6,}$/;
  // 密码长度校验
  if (!reg.test(value)) {
    return callback(new Error('密码长度必须大于等于6位，且只能包含字母和数字'));
  }
  if (value === ruleForm.originalPwd) {
    return callback(new Error('新密码不能与原密码相同'));
  }
  return callback(); // 校验通过
}

//重复密码校验
const checkPwd2 = (rules: any, value: any, callback: any) => {
  rules
  if (!value) {
    return callback(new Error('输入不能为空'))
  }
  if (value !== ruleForm.newPwd) {
    return callback(new Error('两次输入的密码不一致'));
  }
  return callback(); // 校验通过
}

//校验规则数组
const rules = reactive<FormRules<typeof ruleForm>>({
  originalPwd: [{ validator: checkOriginalPwd, trigger: 'blur' }],
  newPwd: [{ validator: checkPwd, trigger: 'blur' }],
  newPwd2: [{ validator: checkPwd2, trigger: 'blur' }],
})


//修改密码函数
async function handleUpdate() {
  // 调用修改密码接口
  const response = await UpdateApi(ruleForm);
  console.log('调用了修改密码方法', response);
  //清空表单数据
  ruleForm.originalPwd = '';
  ruleForm.newPwd = '';
  ruleForm.newPwd2 = '';
  if (response.code === 200) {
    ElMessageBox.confirm(
      '修改密码成功，请重新进行登录！',
      {
        confirmButtonText: '确定',
        type: 'success',
      }
    ).then(async () => {
      router.push('/')
    }).catch(() => {
      ElMessage.info('已取消');
    });
  } else {
    ElMessage.error('修改密码失败');
  }
}

//提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      handleUpdate();
    } else {
      ElMessage({
        message: '请按要求输入数据',
        type: 'error',
        duration: 2000, // 消息提示框显示的时间，单位是毫秒
      });
    }
  })
}

// 键盘事件处理函数
const handleKeyDown = (event: any) => {
  if (event.key === 'Enter') {
    submitForm(ruleFormRef.value);
  }
};

onMounted(() => {
  window.addEventListener('keydown', handleKeyDown);
});

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown);
});
</script>
  
<style scoped>
.container {
  /* background-image: src('@/assets/3.jpg'); */
  border-radius: 10px;
  padding-top: 80px;
  padding-bottom: 30px;
  background-color: aqua;
  margin: 30px auto;
  width: 500px
}
</style>